<template>
	<view class="content">
		<button @click="handleupload">选择PDF</button>

		<scroll-view scroll-y="true" class="scrollView">
			<view class="imageItem">
				<image v-for="(item, index) in imageList" :key="index" :src="item" mode="widthFix" @longpress="saveImage(item, index)"></image>
			</view>
		</scroll-view>

		<nkselectfile v-model="selectfileStatus" :filterArr="['pdf']" titel="选择文件" btnText="确定" @confirm="fileSelect" @change="fileChange"></nkselectfile>
	</view>
</template>

<script>
const pdftoimage = uni.requireNativePlugin('wrc-pdftoimage');
import nkselectfile from '@/components/nk-select-file/nk-select-file.vue';
export default {
	components: {
		nkselectfile
	},
	data() {
		return {
			selectfileStatus: false,
			imageList: []
		};
	},
	methods: {
		saveImage(item, index) {
			uni.saveImageToPhotosAlbum({
				filePath: item,
				success: function () {
					console.log('save success');
				}
			});
		},

		// 上传文件
		handleupload() {
			console.log('选择文件');
			// 查询是否有android.permission.READ_EXTERNAL_STORAGE权限访问
			plus.android.requestPermissions(
				['android.permission.READ_EXTERNAL_STORAGE'],
				(permissions) => {
					console.log(permissions, '权限申请');
					this.selectfileStatus = true;
				},
				(e) => {
					uni.showToast({
						icon: 'none',
						title: '请确认授权访问',
						duration: 2000
					});
				}
			);
		},

		fileSelect(e) {
			this.imageList = [];
			let url = e[0].url;
			console.log(url, '选择的pdf');
			uni.showLoading({
				title: '加载中'
			});
			pdftoimage.changePdfToImage(url, {}, (res) => {
				console.log(res, '转换的数据');
				let data = res.data;
				for (let i = 0; i < data.length; i++) {
					let base64 = 'data:image/jpeg;base64,' + data[i];
					this.imageList.push(base64);
				}
				uni.hideLoading();
			});
		},
		fileChange() {
			this.selectfileStatus = false;
		}
	}
};
</script>

<style lang="scss" scoped>
.content {
	background-color: #f8f8f8;
}
.scrollView {
	width: 100vw;
	height: calc(100vh - 100rpx);

	.imageItem {
		padding: 0rpx 20rpx;

		image {
			width: 100%;
		}
	}
}
</style>
